package controller;

import dao.DaoException;
import dao.userDao.UserDaoImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        boolean success_login = false;
        String user = request.getParameter("username");
        String psd = request.getParameter("password");

        UserDaoImp dao = new UserDaoImp();
        try {
            success_login = dao.success_login(user, psd);
        } catch (DaoException e) {
            e.printStackTrace();
        }


        request.setAttribute("username", user);
        if (success_login) {
            session.setAttribute("user", user);
            request.getRequestDispatcher("/shopping.jsp").forward(request, response);
        } else {
            request.setAttribute("errorMsg", "用户名或密码不正确");
        }
        request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
    }
}